package org.cfx.auth.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.cfx.auth.domain.dto.LoginDto;
import org.cfx.auth.service.impl.LoginServiceImpl;
import org.cfx.basic.myenum.LoginContext;
import org.cfx.basic.util.AjaxResult;
import org.cfx.basic.util.RedisUtil;
import org.cfx.org.domain.Employee;
import org.cfx.org.domain.dto.EmployeeDto;
import org.cfx.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


import java.util.Map;

/**
 * @author RTX 9090
 */
@RestController
public class LoginController {

    @Autowired
    private LoginServiceImpl loginService;

    @Autowired
    private RedisUtil redisUtil;

    @PutMapping("/login")
    public AjaxResult login(@RequestBody LoginDto loginDto){
        try {
            Map<String, Object> loginEmployee = loginService.login(loginDto);
            return AjaxResult.me().setData(loginEmployee);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
    @PutMapping("/login2")
    public AjaxResult login2(@RequestBody LoginDto loginDto,HttpServletRequest request){
        try {
            EmployeeDto employeeDto = loginService.login2(loginDto, request);
            return AjaxResult.me().setData(employeeDto);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }

    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request){
        try {
//            System.out.println(LoginContext.CONTEXT.getMap());
            String token = request.getHeader("TOKEN");
//            System.out.println("前"+LoginContext.CONTEXT.getMap().get(token));
//            LoginContext.CONTEXT.getMap().remove(token);
//            System.out.println("后"+LoginContext.CONTEXT.getMap().get(token));
            redisUtil.getKey(token);
            redisUtil.logout(token);
            redisUtil.getKey(token);
            return AjaxResult.me().setSuccess(true).setMessage("登出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("登出失败");
        }
    }

}
